package dproxy.application.ui.commands;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import dproxy.application.ui.CommandLineProcessor;
import dproxy.server.cache.bo.CacheBO;
import dproxy.server.cache.to.RequestResponse;
import dproxy.server.common.util.UtilRead;

/**
 * Import a user-edited entry
 * Usage:
 * import index N
 */
public class Import implements Command {

	/** Sub-Command that will export a determined entry. */
	private static final String SC_INDEX = "index";
	
    /** File name. */
    private int requestNumber;
    
    /**
     * @see dproxy.application.ui.commands.Command#description()
     */
    public String description() {
        return 
            "   'import'     - Imports an user-edited entry\n" +
            "                  - Options:\n" +
            "                    " + SC_INDEX + " N - Exported request number";
    }                            
    
    /**
     * @see dproxy.application.ui.commands.Command#validate(Collection)
     */
    public void validate(Collection<String> parameters) throws ValidationException {
        Iterator <String> itParameters = parameters.iterator();
        if (itParameters.hasNext()) {
        	String subCommand = itParameters.next();
			if (SC_INDEX.equals(subCommand)) {
				requestNumber = ValidationUtils.getNumberParameter(itParameters);
	            ValidationUtils.validateNoMoreParameters(itParameters);
			} else {
				throw new ValidationException();
			}
        } else {
            throw new ValidationException();
        }
        
    }

    /**
     * @see dproxy.application.ui.commands.Command#confirm()
     */
    public boolean confirm() {
        // No need for confirmation:
        return true;
    }
    
    /**
     * @see dproxy.application.ui.commands.Command#execute()
     */
    public void execute() {
    	InputStream isRequestKey = null;
    	InputStream isRequest = null;
    	InputStream isResponse = null;
    	
    	try {
    		String nameRequestKey = Export.BASE_NAME + Export.KEY + requestNumber + Export.EXTENSION;
			String nameRequest = Export.BASE_NAME + Export.REQUEST + requestNumber + Export.EXTENSION;
			String nameResponse = Export.BASE_NAME + Export.RESPONSE + requestNumber + Export.EXTENSION;
			
			isRequestKey = new FileInputStream(nameRequestKey);
			isRequest = new FileInputStream(nameRequest);
			isResponse = new FileInputStream(nameResponse);

    		RequestResponse rr = new RequestResponse();
    		rr.setDate(new Date());
    		rr.setIndex(requestNumber);
    		rr.setKey(UtilRead.readToString(isRequestKey));
    		rr.setRequestContents(UtilRead.readToByteArray(isRequest));
    		rr.setResponseContents(UtilRead.readToByteArray(isResponse));
    		
	        CacheBO.getInstance().importFromUser(rr);
	        CommandLineProcessor.getInstance().write("Entry " + requestNumber + " succesfully imported");
		} catch (FileNotFoundException e) {
			CommandLineProcessor.getInstance().write("File not found: " + e.getMessage());
		} finally {
			if (isRequestKey != null) {
				try {
					isRequestKey.close();
				} catch (IOException e) {
					CommandLineProcessor.getInstance().write("Error closing file: " + e.getMessage());
				}
			}
			if (isRequest != null) {
				try {
					isRequest.close();
				} catch (IOException e) {
					CommandLineProcessor.getInstance().write("Error closing file: " + e.getMessage());
				}
			}
			if (isResponse != null) {
				try {
					isResponse.close();
				} catch (IOException e) {
					CommandLineProcessor.getInstance().write("Error closing file: " + e.getMessage());
				}
			}
		}
    }

}
